<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import dial from './dial.vue'
import { getAllApi, addApi, updateByIdApi } from '@/api/warehousingentry/warehousingEntryDetailsSort'
import { getInfoApi } from '@/api/warehousingentry/warehousingEntryDetails'
import { getSkuInfoApi } from '@/api/item'
import { ElMessage } from 'element-plus'
import eventBus from '@/utils/eventBus'

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const size = ref('default')
const background = ref(true)
const disabled = ref(false)

const handleSizeChange = (val) => {
  pageSize.value = val
  getAll()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getAll()
}

const form = ref({
  warehousingEntryDetailsId: null,
  skuId: null
})

const statusMap = {
  1: '分拣中',
  2: '已完成分拣',
  3: '已上架'
}

const getAll = async () => {
  let res = await getAllApi(
    currentPage.value,
    pageSize.value
  )
  total.value = res.total
  tableData.value = res.rows
}
const itemInfo = ref()
const getItemList = async () => {
  let res = await getInfoApi()
  itemInfo.value = res
}

const diaRef = ref(null)
const getItemNameById = (skuId) => {
  if (!diaRef.value || !diaRef.value.itemInfo) {
    return '未知商品'
  }
  for (const item of diaRef.value.itemInfo) {
    if (item.id === skuId) {
      return item.title
    }
  }
  return '未知商品'
}
const getItemCodeById = (skuId) => {
  if (!diaRef.value || !diaRef.value.itemInfo) {
    return '未知商品'
  }
  for (const item of diaRef.value.itemInfo) {
    if (item.id === skuId) {
      return item.subtitle
    }
  }
  return '未知商品'
}

const handleEdit = (row) => {
  diaRef.value.dialogFormData = { ...row }
  diaRef.value.dialogVisible = true
}

const search = () => {
  currentPage.value = 1
  getAll()
}

const ids = ref([])
const handleSelectionChange = (val) => {
  ids.value = val.map(item => item.id)
}

const updateData = ref({
  count: '',
  id: '',
})
const confirm = async (row) => {
  // const sortDataList = {
  //   skuId: row.skuId,
  //   count: row.count,
  //   warehousingEntryDetailsId: row.id,  // ← 原始明细ID
  //   status: 1,
  //   damageCount: 0,
  //   surpassCount: 0,
  //   lackCount: 0,
  //   saasId: row.saasId,
  //   createBy: 'system'
  // }
  // const sortRes = await addApi(sortDataList)
  // if (sortRes.code) {
  updateData.value.count = row.count
  updateData.value.id = row.id
  let res = null
  res = await updateByIdApi(updateData.value)
  if (res.code) {
    getAll()
  } else {
    ElMessage.error('确认失败')
  }
  eventBus.emit('refreshSortPage')
  // } else {
  //   ElMessage.warning('入库确认成功，但转交分拣管理失败！')
  //   }
  if (res.code) {
    ElMessage.success('操作成功!')
    resetForm()
    getAll()
  } else {
    ElMessage.error('操作失败！')
  }
}
const getItemInfoById = (warehousingEntryDetailsId) => {
  if (!itemInfo.value) {
    return '0'
  }
  for (const item of itemInfo.value) {
    if (item.id === warehousingEntryDetailsId) {
      return item.count
    }
  }
  return '0'
}

defineExpose({
  refreshData: getAll
})

onMounted(() => {
  getAll()
  getItemList()
  eventBus.on('refreshSortPage', getAll)
})
// 组件卸载时移除事件监听
onUnmounted(() => {
  eventBus.off('refreshSortPage', getAll)
})
</script>

<template>
  <dial ref="diaRef" @refresh="getAll" />
  <el-form :model="form" :inline="true" style="float: right;">
    <!-- <el-form-item>
      <el-button @click="handleAdd" type="primary">新增</el-button>
    </el-form-item> -->
    <el-form-item>
      <el-input v-model="form.warehousingEntryDetailsId" placeholder="入库明细ID" />
    </el-form-item>
    <el-form-item>
      <el-input v-model="form.skuId" placeholder="规格ID" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column property="count" label="分拣数量" />
    <el-table-column property="skuId" label="规格ID" />
    <el-table-column property="skuId" label="商品名称" />
    <el-table-column property="skuId" label="规格名称" />
    <el-table-column property="status" label="状态">
      <template #default="{ row }">{{ statusMap[row.status] }}</template>
    </el-table-column>
    <el-table-column property="warehousingEntryDetailsId" label="总数量">
      <template #default="{ row }">
        {{ getItemInfoById(row.warehousingEntryDetailsId) }}
      </template>
    </el-table-column>
    <el-table-column property="damageCount" label="破损个数" />
    <el-table-column property="surpassCount" label="超出数量" />
    <el-table-column property="lackCount" label="缺少数量" />
    <el-table-column property="createTime" label="创建时间" />
    <el-table-column fixed="right" label="操作" width="450">
      <template #default="{ row }">
        <el-button type="primary" @click="handleEdit(row)">分拣</el-button>
        <!-- <el-button type="primary" @click="handleEdit(row)">编辑</el-button> -->
        <el-button type="primary" @click="confirm(row)">完成分拣</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>